package org.emavaj.sanguosha.view.dialog;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;

import org.apache.log4j.Logger;
import org.emavaj.common.ImageUtil;
import org.emavaj.common.annotation.ActionListenerFor;
import org.emavaj.common.annotation.ActionListenerInstaller;
import org.emavaj.sanguosha.controller.server.GameServer;
import org.emavaj.sanguosha.model.constants.Constants;
import org.emavaj.sanguosha.view.MainFrame;
import org.emavaj.sanguosha.view.component.EmptyComponent;

import craky.component.JImagePane;
import craky.componentc.GridBorder;
import craky.componentc.JCButton;
import craky.componentc.JCCheckBox;
import craky.componentc.JCComboBox;
import craky.componentc.JCLabel;
import craky.componentc.JCMessageBox;
import craky.componentc.JCSpinner;
import craky.componentc.JCTextField;
import craky.layout.LineLayout;

/**
 * 服务器启动对话框
 * <p/>
 * User: DIZEM Time: 11-3-30 下午11:07
 * 
 * eMavaj updated 20120914
 */
//public class StartServerDialog extends JDialog implements ActionListener {
public class StartServerDialog extends JDialog {

	private static final long serialVersionUID = 9024425419662461539L;

	private static Logger log = Logger.getLogger(StartServerDialog.class);

	private MainFrame mainFrame;

	private JLabel lblServerName;
	private JTextField txtServerName;
	private JLabel lblTimeDelay;
	private JSpinner txtTimeDelay;
	private JLabel lblIp;
	private JTextField txtIp;
	private JLabel lblPort;
	private JTextField txtPort;
	private JButton btnStart;
	private JButton btnCancel;
	private JButton btnGetWLanIp;
	private JCheckBox checkNoTimeDelay;
	private JLabel lblGameType;
	private JComboBox cbGameType;

	/**
	 * 构造函数
	 * 
	 * @param owner
	 *            父窗体
	 */
	public StartServerDialog(Window owner) {
		super(owner, "启动服务器", ModalityType.DOCUMENT_MODAL);
		mainFrame = (MainFrame) owner;

		getContentPane().setPreferredSize(new Dimension(300, 200));
		// 窗口图标
		setIconImage(ImageUtil.getImage("sgs.png"));
		setSize(new Dimension(300, 200));
		setLayout(new BorderLayout());
		// 主要输入框
		add(createMainPane(), BorderLayout.CENTER);
		// 按钮
		add(createBottomPane(), BorderLayout.SOUTH);
		// 注册监听时间
		ActionListenerInstaller.processAnnotation(this);
		//
		pack();
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setResizable(false);
		setLocationRelativeTo(owner);
		setVisible(true);
	}

	/**
	 * 创建主界面
	 * 
	 * @return
	 */
	private JImagePane createMainPane() {
		// 输入框部分面板
		JImagePane mainPane = new JImagePane();
		// 输入框部分面板颜色
		mainPane.setBackground(new Color(228, 244, 255));
		mainPane.setBorder(new GridBorder(Color.WHITE, 0, 1, 0, 1));
		mainPane.setLayout(new LineLayout(0, 0, 0, 0, 0, LineLayout.LEADING,
				LineLayout.LEADING, LineLayout.VERTICAL));

		// label “服务器名”
		lblServerName = new JCLabel("\u670d\u52a1\u5668\u540d");
		lblServerName.setBorder(new EmptyBorder(1, 0, 0, 10));
		lblServerName.setPreferredSize(new Dimension(74, 24));
		lblServerName.setHorizontalAlignment(JCLabel.RIGHT);

		// 服务器名输入框
		txtServerName = new JCTextField();
		txtServerName.setPreferredSize(new Dimension(-1, 26));
		txtServerName.setEditable(true);
		// 服务器名输入框内默认文字 主机名 +“的服务器”
		txtServerName.setText(getUserName() + "\u7684\u670d\u52a1\u5668");

		// 占位容器，表示面板的一行
		EmptyComponent ecServerName = new EmptyComponent();
		ecServerName.setBorder(new EmptyBorder(0, 0, 0, 40));
		ecServerName.setLayout(new LineLayout(0, 0, 0, 14, 0,
				LineLayout.LEADING, LineLayout.LEADING, LineLayout.HORIZONTAL));
		ecServerName.setPreferredSize(new Dimension(-1, 50));
		ecServerName.add(lblServerName, LineLayout.START);
		ecServerName.add(txtServerName, LineLayout.MIDDLE);

		// Double current = new Double(15);
		// Double min = new Double(5);
		// Double max = new Double(30);
		// Double step = new Double(1);
		SpinnerNumberModel m_numberSpinnerModel = new SpinnerNumberModel(
				Double.valueOf(15), Double.valueOf(5), Double.valueOf(30),
				Double.valueOf(1));
		// 出牌时间选择器 5 ~ 15 ~ 30
		txtTimeDelay = new JCSpinner(m_numberSpinnerModel);
		txtTimeDelay.setAlignmentX(Component.RIGHT_ALIGNMENT);
		// label “出牌时间”
		lblTimeDelay = new JCLabel("\u51fa\u724c\u65f6\u95f4");
		lblTimeDelay.setBorder(new EmptyBorder(1, 0, 0, 10));
		lblTimeDelay.setPreferredSize(new Dimension(74, 24));
		lblTimeDelay.setHorizontalAlignment(JCLabel.RIGHT);
		// label “不限时间”
		checkNoTimeDelay = new JCCheckBox("\u4e0d\u9650\u65f6\u95f4");
		checkNoTimeDelay.setBorder(new EmptyBorder(1, 20, 10, 0));
		//checkNoTimeDelay.addActionListener(this);
		// label “秒”
		JLabel lblSecond = new JCLabel("\u79d2");
		lblSecond.setBorder(new EmptyBorder(4, 3, 5, 10));
		
		// 占位第二行	出牌时间设置
		EmptyComponent ecTimeDelay = new EmptyComponent();
		ecTimeDelay.setBorder(new EmptyBorder(0, 0, 0, 100));
		ecTimeDelay.setLayout(new LineLayout(0, 0, 0, 0, 0, LineLayout.LEADING,
				LineLayout.LEADING, LineLayout.HORIZONTAL));
		ecTimeDelay.setPreferredSize(new Dimension(-1, 35));
		ecTimeDelay.add(lblTimeDelay, LineLayout.START);
		ecTimeDelay.add(txtTimeDelay, LineLayout.START);
		ecTimeDelay.add(lblSecond, LineLayout.START);
		ecTimeDelay.add(checkNoTimeDelay, LineLayout.END_FILL);

		// label “服务器地址”
		lblIp = new JCLabel("\u670d\u52a1\u5668\u5730\u5740");
		lblIp.setBorder(new EmptyBorder(1, 0, 0, 10));
		lblIp.setPreferredSize(new Dimension(74, 24));
		lblIp.setHorizontalAlignment(JCLabel.RIGHT);
		// 本机地址
		txtIp = new JCTextField("127.0.0.1");
		txtIp.setEditable(false);
		txtIp.setPreferredSize(new Dimension(100, 26));
		// label “端口”
		lblPort = new JCLabel("\u7aef\u53e3");
		lblPort.setBorder(new EmptyBorder(1, 0, 0, 5));
		lblPort.setPreferredSize(new Dimension(50, 24));
		lblPort.setHorizontalAlignment(JCLabel.RIGHT);

		txtPort = new JCTextField("7777");
		txtPort.setPreferredSize(new Dimension(40, 26));

		// 占位第三行
		EmptyComponent ecIp = new EmptyComponent();
		ecIp.setBorder(new EmptyBorder(0, 0, 0, 90));
		ecIp.setLayout(new LineLayout(0, 0, 0, 0, 0, LineLayout.LEADING,
				LineLayout.LEADING, LineLayout.HORIZONTAL));
		ecIp.setPreferredSize(new Dimension(-1, 35));
		ecIp.add(lblIp, LineLayout.START);
		ecIp.add(txtIp, LineLayout.START);
		ecIp.add(lblPort, LineLayout.START);
		ecIp.add(txtPort, LineLayout.START);

		EmptyComponent ecBtnIp = new EmptyComponent();
		ecBtnIp.setBorder(new EmptyBorder(0, 75, 0, 90));
		ecBtnIp.setLayout(new LineLayout(0, 0, 0, 0, 0, LineLayout.LEADING,
				LineLayout.LEADING, LineLayout.HORIZONTAL));
		ecBtnIp.setPreferredSize(new Dimension(-1, 35));

		btnGetWLanIp = new JCButton("\u63a2\u6d4b\u5e7f\u57df\u7f51IP");
		btnGetWLanIp.setPreferredSize(new Dimension(120, 21));
		btnGetWLanIp.setHorizontalAlignment(JCButton.CENTER);
		//btnGetWLanIp.addActionListener(this);
		ecBtnIp.add(btnGetWLanIp, LineLayout.START);

		lblGameType = new JCLabel("\u6e38\u620f\u6a21\u5f0f");
		lblGameType.setBorder(new EmptyBorder(1, 0, 5, 10));
		lblGameType.setPreferredSize(new Dimension(74, 24));
		lblGameType.setHorizontalAlignment(JCLabel.RIGHT);
		cbGameType = new JCComboBox(new String[] { "\u4e24\u4eba\u5c40",
				"\u4e09\u4eba\u5c40", "\u56db\u4eba\u5c40",
				"\u4e94\u4eba\u5c40" });
		cbGameType.setPreferredSize(new Dimension(100, 21));
		EmptyComponent ecGameType = new EmptyComponent();
		ecGameType.setBorder(new EmptyBorder(0, 0, 0, 60));
		ecGameType.setLayout(new LineLayout(0, 0, 0, 0, 0, LineLayout.LEADING,
				LineLayout.LEADING, LineLayout.HORIZONTAL));
		ecGameType.setPreferredSize(new Dimension(-1, 35));
		ecGameType.add(lblGameType, LineLayout.START);
		ecGameType.add(cbGameType, LineLayout.START);

		mainPane.add(ecServerName, LineLayout.START_FILL);
		mainPane.add(ecTimeDelay, LineLayout.START_FILL);
		mainPane.add(ecIp, LineLayout.START_FILL);
		mainPane.add(ecBtnIp, LineLayout.START_FILL);
		mainPane.add(ecGameType, LineLayout.START_FILL);
		return mainPane;
	}

	/**
	 * 创建底栏
	 * 
	 * @return
	 */
	private JImagePane createBottomPane() {
		JImagePane bottomPane = new JImagePane();
		bottomPane.setPreferredSize(new Dimension(334, 30));
		bottomPane.setImage(ImageUtil.getImage("dialog_bottom.png"));
		bottomPane.setPreferredSize(new Dimension(334, 30));
		bottomPane.setBorder(new EmptyBorder(0, 0, 0, 0));
		bottomPane.setLayout(new LineLayout(5, 5, 7, 5, 0, LineLayout.LEADING,
				LineLayout.LEADING, LineLayout.HORIZONTAL));
		btnStart = new JCButton("\u542f\u52a8(S)");
		btnStart.setPreferredSize(new Dimension(73, 21));
		btnStart.setMnemonic('R');
		//btnStart.addActionListener(this);
		btnCancel = new JCButton("\u53d6\u6d88(C)");
		btnCancel.setPreferredSize(new Dimension(73, 21));
		btnCancel.setMnemonic('C');
		//btnCancel.addActionListener(this);
		bottomPane.add(btnStart, LineLayout.END);
		bottomPane.add(btnCancel, LineLayout.END);
		return bottomPane;
	}
	
	/**
	 * 当选择没有时间限制时，禁用时间选择器
	 */
	@ActionListenerFor(source = "checkNoTimeDelay")
	public void noTimeDelayHandler() {
		txtTimeDelay.setEnabled(!txtTimeDelay.isEnabled());
	}
	
	/**
	 * 查找WLenIP，失败则弹框提示
	 */
	@ActionListenerFor(source = "btnGetWLanIp")
	public void getWLanIpHandler() {
		try {
			txtIp.setText(InetAddress.getLocalHost().getHostAddress());
		} catch (UnknownHostException e1) {
			log.error("Host unknown");
			JCMessageBox
					.createErrorMessageBox(this, "Error",
							"\u65e0\u6cd5\u627e\u5230\u4e3b\u673aIP, \u8bf7\u624b\u52a8\u8bbe\u7f6e")
					.open();
		}
	}
	
	/**
	 * 退出创建服务器
	 */
	@ActionListenerFor(source = "btnCancel")
	public void cancelHandler() {
		this.dispose();
	}
	
	/**
	 * 创建服务器前，检查IP格式
	 */
	@ActionListenerFor(source = "btnStart")
	public void ipCheckHandler() {
		if (!txtIp.getText().matches(Constants.PATTERN_IP)) {
			JCMessageBox.createErrorMessageBox(this, "Error", "IP地址格式错误")
					.open();

		} else if (!txtPort.getText().matches(Constants.PATTERN_PORT)) {
			JCMessageBox.createErrorMessageBox(this, "Error", "端口格式错误")
					.open();

		} else {
			// 显示日志
			mainFrame.startOrStopServer();
			// 创建并设置服务器
			mainFrame.setServer(new GameServer(mainFrame, txtServerName
					.getText(), Integer.parseInt(txtPort.getText()),
					checkNoTimeDelay.isSelected() ? -1
							: (int) Double.parseDouble(txtTimeDelay
									.getValue().toString()), cbGameType
							.getSelectedIndex() + 2));
			this.dispose();
		}
	}

//	/**
//	 * 处理事件
//	 * 
//	 * @param e
//	 */
//	public void actionPerformed(ActionEvent e) {
//
//		if (e.getSource() == checkNoTimeDelay) {
//			txtTimeDelay.setEnabled(!txtTimeDelay.isEnabled());
//
//		} else if (e.getSource() == btnGetWLanIp) {
//
//			try {
//				txtIp.setText(InetAddress.getLocalHost().getHostAddress());
//
//			} catch (UnknownHostException e1) {
//				log.error("Host unknown");
//				JCMessageBox
//						.createErrorMessageBox(this, "Error",
//								"\u65e0\u6cd5\u627e\u5230\u4e3b\u673aIP, \u8bf7\u624b\u52a8\u8bbe\u7f6e")
//						.open();
//			}
//
//		} else if (e.getSource() == btnCancel) {
//			this.dispose();
//
//		} else if (e.getSource() == btnStart) {
//			if (!txtIp.getText().matches(PATTERN_IP)) {
//				JCMessageBox.createErrorMessageBox(this, "Error", "IP地址格式错误")
//						.open();
//
//			} else if (!txtPort.getText().matches(PATTERN_PORT)) {
//				JCMessageBox.createErrorMessageBox(this, "Error", "端口格式错误")
//						.open();
//
//			} else {
//
//				mainFrame.startOrStopServer();
//				mainFrame.setServer(new GameServer(mainFrame, txtServerName
//						.getText(), Integer.parseInt(txtPort.getText()),
//						checkNoTimeDelay.isSelected() ? -1
//								: (int) Double.parseDouble(txtTimeDelay
//										.getValue().toString()), cbGameType
//								.getSelectedIndex() + 2));
//				this.dispose();
//			}
//		}
//	}

	/**
	 * 获取主机名称
	 * 
	 * @return
	 */
	public String getUserName() {
		Map<String, String> map = System.getenv();
		return map.get("USERNAME");
	}
}
